import React, { FC } from "react";
import { QuestionCheckboxType, listType } from "./tepy";
import { PlusOutlined, MinusCircleOutlined } from "@ant-design/icons";
import { Form, Input, Checkbox, Button, Space } from "antd";

const PropsComponent: FC<QuestionCheckboxType> = (props) => {
  const { title = "", isvertical = "", list = [], onchange, disabled = false } = props;
  const [form] = Form.useForm();
  function valueChangeHandle() {
    if (onchange) {
      const newvalues = form.getFieldsValue() as QuestionCheckboxType;
      const { list = [] } = newvalues;
      list.forEach((item: listType) => {
        if (item.value) return;
        item.value = String(Math.floor(Math.random() * 100000000)).padStart(8, "0");
      });
      onchange(newvalues);
    }
  }
  return (
    <Form initialValues={{ title, isvertical, list }} disabled={disabled} onValuesChange={valueChangeHandle} form={form}>
      <Form.Item label="标题" name="title">
        <Input></Input>
      </Form.Item>
      <Form.List name="list">
        {(fields, { add, remove }) => {
          return (
            <>
              {fields.map(({ key, name }) => {
                return (
                  <Space key={key} align="baseline">
                    <Form.Item name={[name, "checked"]} valuePropName="checked">
                      <Checkbox />
                    </Form.Item>
                    <Form.Item
                      name={[name, "text"]}
                      rules={[
                        { required: true, message: "请输入..." },
                        {
                          validator(_, value) {
                            const { list = [] } = form.getFieldsValue();
                            let num = 0;
                            list.forEach((item: listType) => {
                              if (item.text === value) {
                                num++;
                              }
                            });
                            if (num == 1) {
                              return Promise.resolve();
                            } else {
                              return Promise.reject(new Error("和其他选项重复了"));
                            }
                          },
                        },
                      ]}
                    >
                      <Input placeholder="请输入" />
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(name)} />
                  </Space>
                );
              })}
              <Form.Item>
                <Button type="dashed" onClick={() => add({ text: "", value: "", checked: false })} block icon={<PlusOutlined />}>
                  添加选项
                </Button>
              </Form.Item>
            </>
          );
        }}
      </Form.List>
      <Form.Item name="isvertical" valuePropName="checked">
        <Checkbox>竖直排列</Checkbox>
      </Form.Item>
    </Form>
  );
};

export default PropsComponent;
